<template>
  <div class="client-info">
    <Title title="客户信息" font-size="16px" style="margin-bottom: 17px;"/>
    <el-form
      ref="formRef"
      :model="paramsObj"
      :rules="formRules"
      :disabled="disabledTaxAmount || editLimt"
      :label-position="formAlign"
      class="lineHeight32"
      label-width="110px">
      <el-row type="flex" class="response-el-row">
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item :class="contrastClientDataKeys.includes('clientId')?'data-is-change':''" label="客户名称" prop="clientId">
            <selectWithoutHttp
              v-model="paramsObj.clientId"
              :remote-method="getClientNameMethods"
              :list-data="clientNameOption"
              :default-list="defaultClientOption"
              :delay="200"
              :placement="'right'"
              :disabled="!hasRouteAuth('crm:orderList:clientInfoEdit')"
              label-name="value"
              extend-class="order-client-select"
              key-name="id"
              filterable
              add-new
              add-new-str="添加新客户"
              remote
              placeholder="搜索匹配"
              @addNewClick="addNewClick"
              @change="clientIdChange($event, false)" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item :class="contrastClientDataKeys.includes('clientId')?'data-is-change':''" label="客户联系人" prop="contactPersonId">
            <selectWithoutHttp
              v-model="paramsObj.contactPersonId"
              :remote-method="contactList"
              :disabled="!hasRouteAuth('crm:orderList:clientInfoEdit') || !paramsObj.clientId"
              :default-list="defaultContactPersonOption"
              :list-data="personList"
              extend-class="order-client-select"
              filterable
              remote
              placeholder="搜索匹配"
              @change="contrastClient"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item :class="{ 'data-is-change': contrastClientDataKeys.includes('actualClientId'), 'required-label': actualClientRequired }" label="实际客户名称" prop="actualClientId">
            <selectWithoutHttp
              v-model="paramsObj.actualClientId"
              :remote-method="getActualClientNameMethods"
              :list-data="actualClientNameOption"
              :default-list="defaultActualClientOption"
              :delay="200"
              :placement="'right'"
              :disabled="!hasRouteAuth('crm:orderList:clientInfoEdit')"
              label-name="value"
              extend-class="order-client-select"
              key-name="id"
              filterable
              clearable
              add-new
              add-new-str="添加新客户"
              remote
              placeholder="搜索匹配"
              @addNewClick="addNewClick"
              @change="clientIdChange($event, true)" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item
            :class="contrastClientDataKeys.includes('actualClientId')?'data-is-change':''"
            label="实际客户联系人"
            prop="actualContactPersonId">
            <selectWithoutHttp
              v-model="paramsObj.actualContactPersonId"
              :remote-method="queryActualContactList"
              :disabled="!hasRouteAuth('crm:orderList:clientInfoEdit') || !paramsObj.actualClientId"
              :default-list="defaultActualContactPersonOption"
              :list-data="actualPersonList"
              extend-class="order-client-select"
              filterable
              clearable
              remote
              placeholder="搜索匹配"
              @change="contrastClient"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="客户订单编号" prop="customerOrderNum">
            <el-input v-model.trim="paramsObj.customerOrderNum" :disabled="!hasRouteAuth('crm:orderList:clientInfoEdit')" type="text" placeholder="请输入" size="small" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="responsive-col-lg-8">
          <el-form-item label="所属集团" prop="actualContactPersonId">
            <el-input v-model="paramsObj.group" size="small" disabled placeholder="客户所属集团"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import Title from '@/components/Title';
// components
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import contrastData from './mixins/contrastData';
// api
import { getContact, getClientName } from '@/api/select';
import { hasRouteAuth } from '@/utils/permission';
// 工具方法
import { validateSelect } from './validator';
import _ from 'lodash';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { Title, selectWithoutHttp },
  mixins: [contrastData, mobileCreate],
  props: {
    isClientDisabled: {
      type: Boolean,
      default: false
    },
    editLimt: {
      type: Boolean,
      default: false
    },
    isOtherInfoDisabled: {
      type: Boolean,
      default: false
    },
    disabledTaxAmount: {
      type: Boolean,
      default: false
    },
    isChangeOrder: { // 是否变更单
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      contactListLoading: false,
      defaultClientOption: [],
      defaultActualClientOption: [],
      defaultActualContactPersonOption: [],
      defaultMarketOption: [], // 默认销售列表
      defaultMastermindOption: [],
      defaultContactPersonOption: [],

      personList: [], // 客户联系人列表，与选中客户联动
      actualPersonList: [], // 实际客户联系人列表，与选中客户联动
      clientNameOption: [], // 客户列表
      actualClientNameOption: [], // 实际客户列表
      marketOption: [], // 销售列表
      marketmindOption: [], // 策划执行人列表
      paramsObj: {
        clientId: '',
        contactPersonId: '',
        actualClientId: '',
        actualContactPersonId: '',
        customerOrderNum: '',
        group: ''
      },
      isActual: false, // 实际客户/联系人
      backupsData: {},
      actualClientRequired: 0,
      formRules: {}
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  watch: {
    'actualClientRequired': {
      handler(val) {
        if (val) {
          this.formRules.actualClientId = [{ required: true, trigger: 'change', validator: validateSelect('请选择实际客户') }];
        } else if (this.formRules.actualClientId) {
          delete this.formRules.actualClientId;
          this.$refs.formRef.clearValidate('actualClientId');
        }
      }
    }
  },
  created() {
    if (!this.isClientDisabled) {
      this.formRules = {
        clientId: [{ required: true, trigger: 'change', validator: validateSelect('请选择客户名称') }],
        contactPersonId: [{ required: true, trigger: 'change', validator: validateSelect('请选择客户联系人') }]
      };
    } else {
      this.formRules = {
      };
    }
    this.getClientNameMethods(null, true);
    this.getActualClientNameMethods(null, true);
  },
  methods: {
    hasRouteAuth,
    // 编辑时注入数据
    insertDetail(item) {
      this.backupsData = JSON.parse(JSON.stringify(item.clientInfo));
      const clientInfo = item.clientInfo;
      if (clientInfo.clientId) this.paramsObj.clientId = clientInfo.clientId;
      if (clientInfo.contactPersonId) this.paramsObj.contactPersonId = clientInfo.contactPersonId;
      if (clientInfo.actualClientId) this.paramsObj.actualClientId = clientInfo.actualClientId;
      if (clientInfo.actualContactPersonId) this.paramsObj.actualContactPersonId = clientInfo.actualContactPersonId;
      if (clientInfo.customerOrderNum) this.paramsObj.customerOrderNum = clientInfo.customerOrderNum;
      if (clientInfo.group) this.clientGroupChange(clientInfo);

      if (this.paramsObj.clientId) { this.contactList(); }
      if (this.paramsObj.actualClientId) { this.queryActualContactList(); }

      this.defaultClientOption = [{ id: clientInfo.clientId, value: clientInfo.clientName }];
      this.defaultContactPersonOption = [{ id: clientInfo.contactPersonId, value: clientInfo.contactPerson }];
      this.defaultActualClientOption = [{ id: clientInfo.actualClientId, value: clientInfo.actualClientName }];
      this.defaultActualContactPersonOption = [{ id: clientInfo.actualContactPersonId, value: clientInfo.actualContactPerson }];
    },
    validateForm(validate = true) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject();
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    // 提供给父组件来获取参数
    getParams() {
      const params = _.cloneDeep(this.paramsObj);
      if (!params.clientId) {
        params.contactPersonId = '';
      }
      if (!params.actualClientId) {
        params.actualContactPersonId = '';
      }
      return params;
    },
    clientIdChange(val, isActual = false) {
      isActual ? this.queryActualContactList() : this.contactList();
      this.paramsObj[isActual ? 'actualContactPersonId' : 'contactPersonId'] = '';
      const optionList = (isActual && val) ? this.actualClientNameOption : this.clientNameOption;
      this.contrastClient(); // 变更单
      // 所属集团如果未填【实际客户名称】以【客户名称】为准，否则以【实际客户名称】为准
      if ((isActual && val) || (!isActual && !this.paramsObj['actualClientId'])) {
        const item = optionList.find(j => j.id === val);
        this.clientGroupChange(item);
      } else if (isActual && !val && this.paramsObj['clientId']) {
        const item = optionList.find(j => j.id === this.paramsObj['clientId']);
        this.clientGroupChange(item);
      }
    },
    clientGroupChange(item) {
      this.paramsObj.group = item.group;
    },
    // 获取客户列表
    getClientNameMethods(name = '', notShowNoAuthTip = false) {
      const param = {
        clientName: name,
        isGetMengliClient: false
      };
      getClientName(param, 1, notShowNoAuthTip).then(res => {
        this.clientNameOption = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取实际客户列表
    getActualClientNameMethods(name = '', notShowNoAuthTip = false) {
      const param = {
        clientName: name,
        isGetMengliClient: false
      };
      getClientName(param, 1, notShowNoAuthTip).then(res => {
        this.actualClientNameOption = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    /** 客户联系人列表：与客户联动 */
    contactList(query = null) {
      this.contactListLoading = true;
      getContact(this.paramsObj.clientId, query).then(res => {
        this.contactListLoading = false;
        this.personList = res.data;
        this.actualClientRequired = res.data[0].actualClientRequired;
      }, result => {
        this.contactListLoading = false;
      });
    },
    /** 客户联系人列表：与客户联动 */
    queryActualContactList(query = null) {
      this.contactListLoading = true;
      getContact(this.paramsObj.actualClientId, query).then(res => {
        this.contactListLoading = false;
        this.actualPersonList = res.data;
      }, result => {
        this.contactListLoading = false;
      });
    },
    addNewClick() {
      if (!this.hasRouteAuth('crm:customer:add')) {
        this.$message.error('您暂无新增客户权限');
        return;
      }
      const routeUrl = this.$router.resolve({ name: 'createCustomer' });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.client-info {
  // max-height: 692px;
  background: #fff;
  padding: 16px 24px 0 24px;
  &::v-deep {
    .el-form-item__label {
      line-height: 32px;
      color: #666;
    }
    .el-form-item__content {
      line-height: 32px;
    }
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
  }
  .required-label {
    ::v-deep {
      .el-form-item__label {
        &::before {
          content: "*";
          color: #F56C6C;
          margin-right: 4px;
        }
      }
    }
  }
}
.data-is-change {
  &::v-deep {
    .el-input__inner {
      color: #FF4E5F;
    }
  }
}
</style>
<style lang="scss">
.order-client-select {
  width: 240px;
}
</style>
